#!/usr/bin/env ruby
# Contents: This is the plugin for the xmms player  
# Purpose: The purpose of this file is to sync with xmms and interact with database manager
# Status:  Done 
require  'xmms'
require  'socket'

module Xmms_Plugin
def Xmms_Plugin.configure()
	port_file = File.open("port.config",File::RDONLY,0777)
	port_num = port_file.readlines
	port_file.close
	@port = port_num[0].chomp("\n").to_i	
	id_file = File.open("XMMS.id",File::CREAT|File::RDWR,0777)
	id_num = id_file.readlines
	if id_num.length == 0 then	
		sock = TCPSocket.open("127.0.0.1",@port.to_i)
		sock.print("\"marco\"")
		m = String.new("")
		m = sock.recv(256)
		arr = m.scan(/\"[^\"]+\"/)
		arr[1] = arr[1].scan(/[^\"]+/)
		@id = arr[1].to_s.to_i
		id_file.write(@id)
	else
		@id = id_num[0]
	end	
	
	id_file.close
end

def Xmms_Plugin.run_plugin(r)
	flagged = 0
	nexted = 0
	message = String.new("")
	while(1)
	  	begin 
			if r.playlist? == true
				nexted = r.get_playlist_pos
				if (r.playing? == true and flagged == 0) then 	
					flagged = 1	
					nexted = r.get_playlist_pos
					song_info = r.get_playlist_title
					s = song_info.scan(/[^-]+/)
					ss = s[1].scan(/[^:]+/)
					message <<"\"increment\""<<" "<<"\"#{@id}\""<<" "<<"\"#{r.get_playlist_file}\""<<" "<<"\"#{s[0]}\""<<" "<<"\"------\""<<" "<<"\"#{ss[1]}\""<<" "<< "\"------\""<< " "<< "\"------\"" <<" " << "\"------\""<< " "<< "\"------\"" <<" "<< "\"------\""
					sock = TCPSocket.open("127.0.0.1",@port.to_i)
					sock.print(message)
					m = String.new("")
					m = sock.recv(4)
					if m != "\"OK\"" then
						print " omg_error"
					end
					message = String.new("")
					sock.close
				end
				if (r.playing? == false and r.paused? == false) then
					flagged = 0
				end
				if (nexted != r.get_playlist_pos) then 
					flagged = 0
				end
			end
		
		rescue Xmms::Error
			break
		end
	end
end

def  Xmms_Plugin.start(r)
	flag = 0
	while(1)
		if r.running? == true then
			if flag == 0 then
				configure()
				flag = 1
			end
			run_plugin(r)
		end
	end
end
end
